//
//  LZAppendImageBar.m
//  laziz_Merchant
//
//  Created by XMac on 17/3/14.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZAppendImageBar.h"
#import "XXNibBridge.h"
#import "Masonry.h"
#import "UIImageView+WebCache.h"
#import "extobjc.h"
#import "UIGestureRecognizer+BlocksKit.h"


@interface LZAppendImageBar ()<XXNibBridge>



/**
 image url地址数组
 */
@property (strong, nonatomic) NSMutableArray<NSString *> * imageUrls;


/**
 image数据字典数组
 */
@property (strong, nonatomic) NSMutableArray<NSDictionary *> * imageDatas;

@property (strong, nonatomic) UIImageView *placeHolderImageView;

@property (strong, nonatomic) __block UIImageView *firstImageView;

@property (strong, nonatomic) __block UIImageView *lastImageView;

@property (assign, nonatomic) NSInteger currentLinesNumber;

@property (copy, nonatomic) void(^process)(MASConstraintMaker *make,BOOL isNextLineOfTheFirst);




@end


@implementation LZAppendImageBar


-(void)awakeFromNib{
    [super awakeFromNib];
    
    self.boundNumber = 5;
    
    _imageUrls = @[].mutableCopy;
    
    //因为使用了xxnib 底层会先调用一次 再去重建 所以UIImageView地址就会有变化,所以这里先去除原先残余的。
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [obj removeFromSuperview];
    }];
    
    
    _placeHolderImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"res_add_license"]];
    
    [self addSubview:self.placeHolderImageView];
    
    [self.placeHolderImageView makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(10);
        make.top.equalTo(10);
        
        make.size.equalTo(CGSizeMake(60, 60));
    }];
    
    [_placeHolderImageView setUserInteractionEnabled:YES];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]bk_initWithHandler:^(UIGestureRecognizer *sender, UIGestureRecognizerState state, CGPoint location) {
        if (self.addPictureBlock) {
            self.addPictureBlock();
        }
    }];
    
    [_placeHolderImageView addGestureRecognizer:tap];
}


-(void (^)(MASConstraintMaker *,BOOL))process{
    if (!_process) {
        //对于折行的处理
        @weakify(self)
        _process = ^(MASConstraintMaker *make,BOOL isNextLineOfTheFirst){
            @strongify(self)
            if (!isNextLineOfTheFirst) {
                make.leading.equalTo(self.lastImageView.trailing).offset(12.5);
                make.top.equalTo(self.lastImageView.top).offset(0);
            }else{
                //约束相对于第一个图片视图
                make.leading.equalTo(self.firstImageView.leading).offset(0);
                make.top.equalTo(self.firstImageView.bottom).offset(12.5);
            }
        };
    }
    return _process;
}

-(void)addTapGes:(UIView *)containerView{
    [containerView setUserInteractionEnabled:YES];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]bk_initWithHandler:^(UIGestureRecognizer *sender, UIGestureRecognizerState state, CGPoint location) {
        if (self.tapPictureBlock) {
            
            self.tapPictureBlock(sender.view.tag,(UIImageView *)sender.view);
        }
    }];
    
    [containerView addGestureRecognizer:tap];
}


-(void)addDeleteView:(UIView *)containerView{
    UIImageView *deleteView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"lz_delete_picture_icon"]];
    
    [containerView addSubview:deleteView];
    
    [deleteView setUserInteractionEnabled:YES];
    
    [deleteView makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(-4);
        make.top.equalTo(4);
        make.size.equalTo(CGSizeMake(17, 17));
    }];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]bk_initWithHandler:^(UIGestureRecognizer *sender, UIGestureRecognizerState state, CGPoint location) {
        if (self.deletePictureBlock) {
            //当前是错差图片
            NSInteger index = sender.view.superview.tag;
            self.deletePictureBlock(self.imageDatas[index][@"id"]);
        }
    }];
    
    [deleteView addGestureRecognizer:tap];
}


/**
 现在是否超过最大宽度了，言外之意就是折行了。
 
 @return .
 */
-(BOOL)isNextLineOfTheFirst:(NSInteger)willLoadIndex{
    
    if (self.currentLinesNumber != 0) {
        willLoadIndex -= self.currentLinesNumber;
    }
    
    //需要的宽度
    CGFloat realWidth = willLoadIndex * 60 + (willLoadIndex - 1) * 12.5 + 20;
    
    BOOL isNeedFoldLine = realWidth > SCREEN_WIDTH;
    
    if (isNeedFoldLine) {
        if (self.currentLinesNumber != 0) {
            self.currentLinesNumber *= 2;
        }else{
            self.currentLinesNumber = willLoadIndex - 1;
        }
    }
    
    return isNeedFoldLine;
}


-(void)loadImages:(NSArray<NSDictionary *> *)images{
    
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj != self.placeHolderImageView) {
            [obj removeFromSuperview];
        }
    }];
    
    self.currentLinesNumber = 0;
    
    _imageDatas = images.mutableCopy;
    
    [self.imageUrls removeAllObjects];
    
    self.firstImageView = nil;
    self.lastImageView = nil;
    
    if (images && images.count > 0) {
        [images enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [self appendImageUrl:obj[@"photoUrl"] needRemarkPlaceHolder:idx == images.count - 1 tag:idx];
        }];
    }else{
        self.placeHolderImageView.hidden = NO;
        [self.placeHolderImageView remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(10);
            make.top.equalTo(10);
        }];
    }
}


-(void)appendImageUrl:(NSString *)imageUrl needRemarkPlaceHolder:(BOOL)isNeed{
    [self appendImageUrl:imageUrl needRemarkPlaceHolder:isNeed tag:self.imageDatas.count - 1];
}


-(void)appendImageUrl:(NSString *)imageUrl needRemarkPlaceHolder:(BOOL)isNeed tag:(NSInteger)tag{
    if (imageUrl) {
        [self.imageUrls addObject:imageUrl];
        
        NSInteger index = self.imageUrls.count;
        
        BOOL isNextLineOfTheFirst =  [self isNextLineOfTheFirst:index];
        
        //增加操作
        UIImageView *tmp = [UIImageView new];
        tmp.tag = tag;
        [self addTapGes:tmp];
        [self addDeleteView:tmp];
        [tmp sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,imageUrl]] placeholderImage:[UIImage imageNamed:@"lz_other_placehoiderImage"]];
        [self addSubview:tmp];
        
        [tmp makeConstraints:^(MASConstraintMaker *make) {
            if (!self.lastImageView) {
                make.leading.equalTo(10);
                make.top.equalTo(10);
            }else{
                self.process(make,isNextLineOfTheFirst);
            }
            
            make.size.equalTo(CGSizeMake(60, 60));
        }];
        
        if (index == 1 || isNextLineOfTheFirst) {
            self.firstImageView = tmp;
        }
        
        self.lastImageView = tmp;
        
        
        if (isNeed) {
            //修正placeholder的位置
            //超过5张就隐藏掉
            if (self.imageDatas.count >= self.boundNumber) {
                self.placeHolderImageView.hidden = YES;
            }else{
                self.placeHolderImageView.hidden = NO;
                [self.placeHolderImageView remakeConstraints:^(MASConstraintMaker *make) {
                    self.process(make,[self isNextLineOfTheFirst:index + 1]);
                }];
            }
        }
    }
}



+(CGFloat)getHeight:(NSInteger)numberOfImageViews boundNumber:(NSInteger)boundNumber{
    //先算一下 一行最多放多少个图片
    
    if (numberOfImageViews < boundNumber) {
        //先加上占位图片
        numberOfImageViews++;
    }
    
    
    NSInteger currentLinesNumber = 0;
    
    for (int willLoadIndex = 0; willLoadIndex < 100; willLoadIndex++) {
        
        if (currentLinesNumber != 0) {
            willLoadIndex -= currentLinesNumber;
        }
        
        //需要的宽度
        CGFloat realWidth = willLoadIndex * 60 + (willLoadIndex - 1) * 12.5 + 20;
        
        BOOL isNeedFoldLine = realWidth > SCREEN_WIDTH;
        
        if (isNeedFoldLine) {
            
            currentLinesNumber = willLoadIndex - 1;
            
            break;
        }
    }
    
    CGFloat result = numberOfImageViews / (CGFloat)currentLinesNumber;
    
    
    return ceil(result) * 100;
}

@end
